<template>
  <div class="app-container">
    <div class="notebook">
      <!-- 标题部分 -->
      <div>
        <h1>📋 任务管理器</h1>
      </div>

      <div v-if="account">
        <textarea
          v-model="newTask"
          placeholder="在这里添加你的任务..."
          rows="4"
        ></textarea>
        <button @click="addTask" :disabled="loading || !newTask">
          添加任务
        </button>
      </div>

      <div v-if="account">
        <h2>任务列表</h2>
        <div class="task-list">
          <div v-for="(task, index) in paginatedTasks" :key="index" class="task-item">
            <p class="task-description">{{ task.description }}</p>
            <p v-if="task.completed" class="task-status completed">任务已完成</p>
            <p v-else class="task-status not-completed">任务未完成</p>
            <button @click="toggleTaskCompletion(index)" class="toggle-button">
              {{ task.completed ? '标记为未完成' : '标记为已完成' }}
            </button>
          </div>
        </div>

        <div class="pagination">
          <button @click="prevPage" :disabled="currentPage === 1">
            上一页
          </button>
          <div v-if="totalPages > 1">
            {{ currentPage }}
          </div>
          <button @click="nextPage" :disabled="currentPage === totalPages">
            下一页
          </button>
        </div>
      </div>

      <div v-if="loading" class="loading-message">
        ⏳ 正在加载，请稍候...
      </div>
    </div>
  </div>
</template>

<script>
import useWeb3 from "./util"; // 确保 useWeb3 正确初始化 Web3 和合约实例

export default {
  data() {
    return {
      account: null,
      newTask: "",
      tasks: [],
      loading: false,
      currentPage: 1,
      itemsPerPage: 6,
      taskContract: null, // 合约实例
      web3: null, // web3 实例
    };
  },
  computed: {
    totalPages() {
      return Math.ceil(this.tasks.length / this.itemsPerPage);
    },
    paginatedTasks() {
      const start = (this.currentPage - 1) * this.itemsPerPage;
      const end = start + this.itemsPerPage;
      return this.tasks.slice(start, end);
    },
  },
  methods: {
    async loadWeb3() {
      const { initWeb3 } = useWeb3();
      try {
        const { web3, taskContract, getAccount } = await initWeb3();
        
        // 保存 web3 和合约实例
        this.web3 = web3;
        this.taskContract = taskContract;

        this.account = await getAccount(); // 获取账户

        if (!this.taskContract) {
          console.error("合约未初始化！");
          return;
        }

        await this.loadTasks();
      } catch (error) {
        console.error("MetaMask 连接失败:", error);
        alert("连接 MetaMask 时出错，请检查钱包设置！");
      }
    },
    async loadTasks() {
      if (!this.taskContract) {
        console.error("任务合约尚未初始化！");
        return;
      }

      try {
        const tasks = await this.taskContract.methods.getTasks().call({
          from: this.account,
        });

        console.log("返回的任务数据:", tasks); // 调试输出

        if (Array.isArray(tasks)) {
          this.tasks = tasks.map((task) => ({
            description: task.description,
            completed: task.completed,
          }));
          this.currentPage = 1;
        } else {
          console.error("返回的数据格式不正确");
          alert("返回的数据格式不正确");
        }
      } catch (error) {
        console.error("加载任务失败:", error);
        alert("加载任务时出错，请稍后再试！");
      }
    },
    async addTask() {
      if (!this.newTask) return alert("请输入任务内容！");
      if (!this.taskContract) {
        console.error("任务合约尚未初始化！");
        return;
      }

      this.loading = true;
      try {
        // 获取 Gas 价格，避免使用 EIP-1559
        const gasPrice = await this.web3.eth.getGasPrice();
        
        await this.taskContract.methods.addTask(this.newTask).send({
          from: this.account,
          gas: 1000000,
          gasPrice: gasPrice, // 使用传统的 Gas 价格
        });
        alert("任务添加成功！");
        this.newTask = "";
        await this.loadTasks();
      } catch (error) {
        console.error("添加任务失败:", error);
        alert("添加任务时出错，请稍后再试！");
      } finally {
        this.loading = false;
      }
    },
    async toggleTaskCompletion(index) {
      if (!this.taskContract) {
        console.error("任务合约尚未初始化！");
        return;
      }

      const task = this.tasks[index];
      try {
        // 获取 Gas 价格，避免使用 EIP-1559
        const gasPrice = await this.web3.eth.getGasPrice();
        
        if (task.completed) {
          await this.taskContract.methods.uncompleteTask(index).send({ 
            from: this.account,
            gasPrice: gasPrice // 使用传统的 Gas 价格
          });
        } else {
          await this.taskContract.methods.completeTask(index).send({ 
            from: this.account,
            gasPrice: gasPrice // 使用传统的 Gas 价格
          });
        }
        await this.loadTasks();
      } catch (error) {
        console.error("更改任务状态失败:", error);
        alert("更改任务状态时出错，请稍后再试！");
      }
    },
    nextPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage++;
      }
    },
    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--;
      }
    },
  },
  async mounted() {
    await this.loadWeb3();
  },
};
</script>

<style scoped>
/* 美化后的黄色色系样式 */
.app-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  font-family: "Roboto", sans-serif;
  background-color: #fef7e3; /* 淡黄色背景 */
}

.notebook {
  width: 90%;
  max-width: 800px;
  padding: 30px;
  background-color: #fff9c4; /* 淡黄色卡片背景 */
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

h1 {
  font-size: 2.5rem;
  color: #f57f17; /* 深黄色 */
  text-align: center;
  margin-bottom: 20px;
}

textarea {
  width: 100%;
  padding: 15px;
  font-size: 1rem;
  border-radius: 8px;
  border: 1px solid #f57f17;
  background-color: #fff3e0; /* 浅橙黄色背景 */
  color: #6d4c41; /* 深咖啡色文字 */
  margin-bottom: 20px;
}

button {
  padding: 12px 20px;
  font-size: 1rem;
  background-color: #f57f17; /* 深黄色按钮 */
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

button:disabled {
  background-color: #e0e0e0; /* 灰色禁用按钮 */
  cursor: not-allowed;
}

button:hover:not(:disabled) {
  background-color: #fb8c00; /* 浅深黄色 */
}

h2 {
  font-size: 1.5rem;
  color: #f57f17;
  margin-bottom: 20px;
}

.task-list {
  margin-bottom: 30px;
}

.task-item {
  background-color: #fff3e0; /* 浅黄色背景 */
  border: 1px solid #f57f17;
  padding: 20px;
  margin-bottom: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.task-description {
  font-size: 1.1rem;
  color: #6d4c41;
  margin-bottom: 10px;
}

.task-status {
  font-size: 1rem;
  margin-bottom: 10px;
}

.completed {
  color: #388e3c; /* 绿色表示已完成 */
}

.not-completed {
  color: #d32f2f; /* 红色表示未完成 */
}

.toggle-button {
  padding: 8px 16px;
  background-color: #f57f17;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.toggle-button:hover {
  background-color: #fb8c00;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
}

.pagination button {
  padding: 10px 20px;
  background-color: #f57f17;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  margin: 0 5px;
}

.pagination button:disabled {
  background-color: #e0e0e0;
  cursor: not-allowed;
}

.loading-message {
  text-align: center;
  font-size: 1rem;
  color: #f57f17;
}
</style>
